<template>
  <div class="production-management">
    <basic-container>
      <!-- 筛选区域 -->
      <el-form :inline="true" size="small" class="filter-form">
        <el-form-item label="日期">
          <el-date-picker v-model="filters.date" type="date" placeholder="选择日期" format="yyyy/MM/dd"
            value-format="yyyy/MM/dd"></el-date-picker>
        </el-form-item>

        <el-form-item label="时段">
          <el-select v-model="filters.period" placeholder="全部">
            <el-option label="全部" value=""></el-option>
            <el-option label="08:00-10:00" value="08:00-10:00"></el-option>
            <el-option label="10:00-12:00" value="10:00-12:00"></el-option>
            <el-option label="13:00-15:00" value="13:00-15:00"></el-option>
            <el-option label="15:00-17:00" value="15:00-17:00"></el-option>
            <el-option label="18:00-20:00" value="18:00-20:00"></el-option>
            <el-option label="20:00-22:00" value="20:00-22:00"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="车间">
          <el-select v-model="filters.workshop" placeholder="全部" @change="getLineList">
            <el-option v-for="item in workShopList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="产线">
          <el-select v-model="filters.line" placeholder="全部">
            <el-option v-for="item in lineShopList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="工位">
          <el-select v-model="filters.station" placeholder="全部">
            <el-option v-for="item in workPositionList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="工序">
          <el-select v-model="filters.process" placeholder="全部">
            <el-option v-for="item in pfocProcessList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">清空</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮区域 -->
      <!--      <div class="operation-bar">
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <div class="action-buttons">
          <el-button
            icon="el-icon-refresh"
            circle
            @click="refreshData"
          ></el-button>
        </div>
      </div>-->
      <!-- 内容 -->
      <!-- 表格区域 -->
      <div style="height: 90%;background: #fff;box-sizing: border-box;padding: 10px;">
        <el-table :data="tableData" border style="width: 100%;height: 92%;" size="small" v-loading="tableLoading">
          <el-table-column type="index" width="50" label="序号"></el-table-column>
          <el-table-column prop="recordDate" label="日期"></el-table-column>
          <el-table-column prop="times" label="时段"></el-table-column>
          <el-table-column prop="workshopName" label="车间"></el-table-column>
          <el-table-column prop="lineName" label="产线" width="60"></el-table-column>
          <el-table-column prop="workshopSetionName" label="工位"></el-table-column>
          <el-table-column prop="workshopProcessName" label="工序"></el-table-column>
          <el-table-column prop="defectRecord" label="不良记录">
            <template slot-scope="scope">
              <el-link type="primary" @click="handleDefectInput(scope.row, 0)">查看</el-link>
            </template>
          </el-table-column>
          <el-table-column prop="createBy" label="创建人"></el-table-column>
          <el-table-column prop="createTime" label="创建时间"></el-table-column>
          <!--        <el-table-column prop="updateBy" label="修改人"></el-table-column>
        <el-table-column prop="updateTime" label="修改时间"></el-table-column>-->
          <el-table-column label="操作" width="180" v-if="false">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="handleDefectInput(scope.row, 1)">不良录入</el-button>
              <el-button size="mini" type="text" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="mini" type="text" @click="handleDelete(scope.row)" style="color: #f56c6c">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
          style="margin-top: 10px"></el-pagination>

      </div>
      <!-- 新增/编辑弹框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="600px">
        <el-form :model="form" :rules="formRules" ref="form" label-width="80px" size="small">
          <el-form-item label="日期" prop="recordDate">
            <el-date-picker v-model="form.recordDate" type="date" placeholder="选择日期" format="yyyy/MM/dd"
              value-format="yyyy/MM/dd" style="width: 100%"></el-date-picker>
          </el-form-item>
          <el-form-item label="时段" prop="times">
            <el-select v-model="form.times" placeholder="请选择时段" style="width: 100%">
              <el-option label="08:00-10:00" value="08:00-10:00"></el-option>
              <el-option label="10:00-12:00" value="10:00-12:00"></el-option>
              <el-option label="13:00-15:00" value="13:00-15:00"></el-option>
              <el-option label="15:00-17:00" value="15:00-17:00"></el-option>
              <el-option label="18:00-20:00" value="18:00-20:00"></el-option>
              <el-option label="20:00-22:00" value="20:00-22:00"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="车间" prop="workshopId">
            <el-select v-model="form.workshopId" placeholder="请选择车间" style="width: 100%">
              <el-option v-for="item in workShopEditList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="产线" prop="lineId">
            <el-select v-model="form.lineId" placeholder="请选择产线" style="width: 100%">
              <el-option v-for="item in lineShopEditList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="工位" prop="workshopSetionId">
            <el-select v-model="form.workshopSetionId" placeholder="请选择工位" style="width: 100%">
              <el-option v-for="item in workPositionEditList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="工序" prop="workshopProcessId">
            <el-select v-model="form.workshopProcessId" placeholder="请选择工序" style="width: 100%">
              <el-option v-for="item in pfocProcessEditList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false" size="small">取消</el-button>
          <el-button type="primary" @click="submitForm" size="small">确定</el-button>
        </div>
      </el-dialog>

      <!-- 不良数据录入弹框 -->
      <el-dialog title="不良数据录入" :visible.sync="defectDialogVisible" :fullscreen="true">
        <div class="defect-info">
          <div class="info-item">
            <span>车间: {{ defectForm.workshopName }}</span>
          </div>
          <div class="info-item">
            <span>产线: {{ defectForm.lineName }}</span>
          </div>
          <div class="info-item">
            <span>工位: {{ defectForm.workshopSetionName }}</span>
          </div>
          <div class="info-item">
            <span>工序: {{ defectForm.workshopProcessName }}</span>
          </div>
        </div>

        <el-form label-width="80px" size="small">
          <div class="defect-table">
            <div v-for="(row, rowIndex) in defectData" :key="rowIndex" class="defect-row">
              <div v-for="(cell, cellIndex) in row" :key="cellIndex" class="defect-cell">
                <div class="ther">子组编号：{{ cell.groupNo }}</div>
                <div style="margin: 10px">
                  <el-input v-model="cell.groupCapacity" placeholder="请输入子组容量" :disabled="isDisabled"></el-input>
                </div>

                <div style="margin: 10px">
                  <el-input v-model="cell.groupFailNum" placeholder="请输入不良数" :disabled="isDisabled"></el-input>
                </div>
              </div>
            </div>
          </div>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="defectDialogVisible = false" size="small">取消</el-button>
          <el-button type="primary" @click="saveDefectData" size="small">保存</el-button>
        </div>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
import {
  fetchList,
  addObj,
  putObj,
  delObj,
  getObj,
  failDetailList,
  addAndUpdatefailDetai,
} from "@/api/pfoc/workorderfailrecord";
import {
  workshop,
  lineList,
  getPfocProcessList,
  getWorkPositionList,
} from "@/api/common.js";
export default {
  data() {
    return {
      filters: {
        date: "",
        period: "",
        workshop: "",
        line: "",
        station: "",
        process: "",
      },
      tableData: [],
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      tableLoading: false,
      dialogFormVisible: false,
      dialogTitle: "新增",
      form: {
        recordDate: "",
        times: "",
        workshopId: "",
        lineId: "",
        workshopSetionId: "",
        workshopProcessId: "",
      },
      formRules: {
        recordDate: [
          { required: true, message: "请选择日期", trigger: "change" },
        ],
        times: [{ required: true, message: "请选择时段", trigger: "change" }],
        workshopId: [
          { required: true, message: "请选择车间", trigger: "change" },
        ],
        lineId: [{ required: true, message: "请选择产线", trigger: "change" }],
        workshopSetionId: [
          { required: true, message: "请选择工位", trigger: "change" },
        ],
        workshopProcessId: [
          { required: true, message: "请选择工序", trigger: "change" },
        ],
      },
      currentRow: null,
      defectDialogVisible: false,
      defectForm: {
        workshop: "",
        line: "",
        station: "",
        process: "",
      },
      defectData: [],
      workShopList: [],
      lineShopList: [],
      pfocProcessList: [],
      workPositionList: [],
      workShopEditList: [],
      lineShopEditList: [],
      workPositionEditList: [],
      pfocProcessEditList: [],
      isDisabled: false,
    };
  },
  mounted() {
    this.fetchTableData();
    this.getWorkshop();
    this.getLineList();
    this.getPfocProcessLists();
    this.getWorkPositionList();
  },

  methods: {
    // 列表查询
    async getWorkshop() {
      const res = await workshop();
      this.workShopList = [
        {
          value: "",
          label: "全部",
        },
        ...res.data.data.records.map((item) => {
          return {
            value: item.id,
            label: item.workshopName,
          };
        }),
      ];
    },
    async getLineList(value) {
      let data = { workshopId: value };
      const res = await lineList(data);
      this.lineShopList = [
        {
          value: "",
          label: "全部",
        },
        ...res.data.data.records.map((item) => {
          return {
            value: item.id,
            label: item.realityLineName,
          };
        }),
      ];
    },
    async getWorkPositionList() {
      let data = { parentId: "1909860013956497410" };
      const res = await getWorkPositionList(data);
      this.workPositionList = [
        {
          value: "",
          label: "全部",
        },
        ...res.data.data.map((item) => {
          return {
            value: item.id,
            label: item.workPositionName,
          };
        }),
      ];
    },
    //工序
    async getPfocProcessLists() {
      const res = await getPfocProcessList();
      this.pfocProcessList = [
        {
          value: "",
          label: "全部",
        },
        ...res.data.data.map((item) => {
          return {
            value: item.id,
            label: item.processName,
          };
        }),
      ];
    },
    handleSearch() {
      let params = new Object();
      params.recordDate = this.filters.date;
      if (this.filters.period != null && this.filters.period != "") {
        let split = this.filters.period.split("-");
        params.startTime = params.recordDate + " " + split[0] + ":00";
        params.endTime = params.recordDate + " " + split[1] + ":00";
      }
      params.workshopId = this.filters.workshop;
      params.lineId = this.filters.line;
      params.workshopSetionId = this.filters.station;
      params.workshopProcessId = this.filters.process;
      this.pagination.currentPage = 1;
      this.fetchTableData(params);
    },
    handleReset() {
      this.filters = {
        date: "",
        period: "",
        workshop: "",
        line: "",
        station: "",
        process: "",
      };
      this.fetchTableData();
    },
    handleAdd() {
      //车间
      this.workShopEditList = this.workShopList;
      this.workShopEditList.splice(0, 1);
      //产线
      this.lineShopEditList = this.lineShopList;
      this.lineShopEditList.splice(0, 1);
      //工位
      this.workPositionEditList = this.workPositionList;
      this.workPositionEditList.splice(0, 1);
      //工序
      this.pfocProcessEditList = this.pfocProcessList;
      this.pfocProcessEditList.splice(0, 1);

      this.dialogTitle = "新增";
      this.currentRow = null;
      this.form = {};
      this.$refs.form && this.$refs.form.resetFields();
      this.dialogFormVisible = true;
    },
    async handleEdit(row) {

      //车间
      this.workShopEditList = this.workShopList;
      this.workShopEditList.splice(0, 1);
      //产线
      this.lineShopEditList = this.lineShopList;
      this.lineShopEditList.splice(0, 1);
      //工位
      this.workPositionEditList = this.workPositionList;
      this.workPositionEditList.splice(0, 1);
      //工序
      this.pfocProcessEditList = this.pfocProcessList;
      this.pfocProcessEditList.splice(0, 1);
      const res = await getObj(row.id);
      this.dialogTitle = "编辑";
      this.currentRow = row;
      this.form = { ...res.data.data };
      this.dialogFormVisible = true;
    },
    handleDelete(row) {
      this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log("删除记录:", row);
          // 调用删除接口
          delObj(row.id).then((res) => {
            this.$message.success("删除成功");
          });
          this.fetchTableData();
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    viewDefectRecord(row) {
      console.log("查看不良记录:", row);

      // 调用查看不良记录接口
    },
    async handleDefectInput(row, type) {
      type == 1 ? (this.isDisabled = false) : this.isDisabled = true
      this.defectForm = {
        workshopName: row.workshopName,
        lineName: row.lineName,
        workshopSetionName: row.workshopSetionName,
        workshopProcessName: row.workshopProcessName,
      };
      let data = { recordId: row.id };
      const res = await failDetailList(data);
      let records = res.data.data.records;
      this.defectData = this.chunkArray(records, 10);
      this.defectDialogVisible = true;
    },
    //组装二维数组
    chunkArray(arr, chunkSize) {
      const result = [];
      for (let i = 0; i < arr.length; i += chunkSize) {
        const resultTml = [];
        let slices = arr.slice(i, i + chunkSize);
        slices.forEach((slice) => {
          let object = new Object();
          object.id = slice.id;
          object.recordId = slice.recordId;
          object.groupNo = slice.groupNo;
          object.groupCapacity = slice.groupCapacity;
          object.groupFailNum = slice.groupFailNum;
          resultTml.push(object);
        });
        result.push(resultTml);
      }
      return result;
    },
    refreshData() {
      console.log("刷新数据");
      this.fetchTableData();
    },
    exportData() {
      console.log("导出数据");
      // 调用导出接口
    },
    moreOptions() {
      console.log("更多选项");
    },
    fetchTableData(params) {
      this.tableLoading = true;
      fetchList(
        Object.assign(
          {
            current: this.pagination.currentPage,
            size: this.pagination.pageSize,
          },
          params,
          this.searchForm
        )
      )
        .then((response) => {
          this.tableData = response.data.data.records;
          this.pagination.total = response.data.data.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.times != null && this.form.times != "") {
            let split = this.form.times.split("-");
            //let s1 = this.form.recordDate.replaceAll("/", "-");
            this.form.startTime = split[0]
            this.form.endTime = split[1]
          } else {
            this.$message.warning("请选择时段");
            return;
          }

          if (this.dialogTitle === "新增") {
            //console.log("新增记录:", this.form);
            addObj(this.form)
              .then((data) => {
                this.$message.success("添加成功");
              })
              .catch(() => {
                //loading()
              });
          } else {
            //console.log("编辑记录:", this.currentRow, this.form);
            // 调用编辑接口
            putObj(this.form)
              .then((data) => {
                this.$message.success("修改成功");
              })
              .catch(() => {
                //loading()
              });
          }
          this.dialogFormVisible = false;
          /*this.$message.success(
            this.dialogTitle === "新增" ? "新增成功" : "编辑成功"
          );*/
          this.fetchTableData();
        }
      });
    },
    saveDefectData() {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      //console.log("保存不良数据:", this.defectForm, this.defectData);
      let thatValues = [];
      this.defectData.forEach((item) => {
        item.forEach((item2) => {
          thatValues.push(item2);
        });
      });
      // 调用保存不良数据接口
      addAndUpdatefailDetai(thatValues)
        .then((data) => {
          this.defectDialogVisible = false;
          this.$message.success("保存成功");
        })
        .catch(() => {
          //this.$message.error("保存失败");
        })
        .finally(() => {
          loading.close();
        });
      //this.defectDialogVisible = false;
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.fetchTableData();
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.fetchTableData();
    },
  },
};
</script>

<style scoped lang="scss">
.filter-form {
  padding: 10px;
  background: #fff;
  margin-bottom: 10px;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.defect-info {
  width: 400px;
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  padding: 10px;
  /* background-color: #f5f7fa; */
  border-radius: 4px;
}

.defect-table {
  display: flex;
  flex-direction: column;
}

.defect-row {
  display: flex;
}
.defect-cell {
  flex: 1;
  // padding: 8px;
  border: 1px solid #ebeef5;
  box-sizing: border-box;
}
.ther {
  padding-left: 10px;
  height: 40px;
  line-height: 40px;
  background-color: #f6f8fa;
}
.dialog-footer {
  text-align: right;
  margin-top: 20px;
}
</style>
